package com.cloudweb.oa.security;

import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.api.ILoginUtil;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.config.JwtProperties;
import com.cloudweb.oa.service.LoginService;
import com.cloudweb.oa.utils.JwtUtil;
import com.cloudweb.oa.utils.SpringUtil;
import com.cloudweb.oa.utils.SysProperties;
import com.cloudweb.oa.utils.SysUtil;
import com.cloudwebsoft.framework.util.LogUtil;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author
 * @create 2019/1/13 12:59
 * @desc
 **/
@Component
public class LoginSuccessAuthenticationHandler implements AuthenticationSuccessHandler {

    @Autowired
    LoginService loginService;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    SysUtil sysUtil;

    @Autowired
    SysProperties sysProperties;

    @Autowired
    ILoginUtil loginUtil;
    @Autowired
    private UserCache userCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String str = null;
        try {
            if (loginService==null) {
                loginService = SpringUtil.getBean(LoginService.class);
            }
            str = loginService.login(request, response, authentication);
        }
        catch (JSONException e) {
            LogUtil.getLog(getClass()).error(e);
        }

        String userName;
        // 如果是 WebSecurityConfig中configure的是DaoAuthenticationProvider，则authentication取到的是org.springframework.security.core.userdetails.User
        if (authentication.getPrincipal() instanceof org.springframework.security.core.userdetails.User) {
            userName = ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername();
        } else {
            userName = (String) authentication.getPrincipal();
        }

        JSONObject json = JSONObject.parseObject(str);
        json.put("code", 200);

        json.put("realName", userCache.getUser(userName).getRealName());

        // 生成 token，防止多重登录
        loginUtil.setLoginInfo(response, userName, json);

        // 登录后事件
        loginUtil.afterLoginSuccess(userName);

        //设置返回请求头
        response.setContentType("application/json;charset=utf-8");

        // 写出流
        PrintWriter out = response.getWriter();
        out.write(json.toJSONString());
        out.flush();
        out.close();
    }
}
